#include "dg_device.h"
#include <string.h>
#include <stdbool.h>
 
struct dg_device *device_list = NULL;
 
static bool dg_device_is_exists( dg_device_t *dev )
{
    dg_device_t *cur = device_list;
    while( cur != NULL )
    {
        if( strcmp(cur->name, dev->name)==0)
        {
            return 1;
        }
        cur = cur->next;
    }
    return 0;
}
 
 
static int device_list_inster(dg_device_t *dev)
{
    dg_device_t *cur = device_list;
    if(NULL == device_list)
    {
        device_list = dev;
        dev->next   = NULL;
    }
    else
    {
        while(NULL != cur->next)
        {
            cur = cur->next;
        }
        cur->next = dev;
        dev->next = NULL;
    }
    return 1;
}
 
/*
    驱动注册
*/
int dg_device_register(dg_device_t *dev)
{
    if((NULL == dev) || (dg_device_is_exists(dev)))
    {
        return 0;
    }
 
    if((NULL == dev->name) ||  (NULL == dev->dops))
    {
        return 0;
    }
    return device_list_inster(dev);
}


dg_device_t *dg_device_find(const char *name)
{
    dg_device_t* cur = device_list;
    while( cur != NULL )
    {
        if( strcmp(cur->name,name)==0)
        {
            return cur;
        }
        cur = cur->next;
    }
    return NULL;
}


int dg_device_read(dg_device_t *dev,  int pos, void *buffer, int size)
{
	if (dev == NULL) return -1;
	if (dev->dops == NULL) return -2;
	if (dev->dops->read == NULL) return -3;
	
    return dev->dops->read(dev, pos, buffer, size);
}


int dg_device_write(dg_device_t *dev, int pos, const void *buffer, int size)
{
    if (dev == NULL) return -1;
	if (dev->dops == NULL) return -2;
	if (dev->dops->write == NULL) return -3;
	
    return dev->dops->write(dev, pos, buffer, size);
}

int dg_device_ctrl(dg_device_t *dev,  int cmd, void *arg)
{
	if (dev == NULL) return -1;
	if (dev->dops == NULL) return -2;
	if (dev->dops->control == NULL) return -3;
	
    return dev->dops->control(dev, cmd, arg);
}
